import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Raw } from 'typeorm';
import { Publish } from '@/entity/form/form.entiy';
import { User } from '@/entity/users/user.entity';

interface UpdateType {
  type: 'rocket' | 'collect' | 'report';
  userId: string;
}

interface Local {
  province: {
    //省
    code: string;
    name: string;
  };
  city?: {
    // 市
    code: string;
    name: string;
  };
  county?: {
    // 区
    code: string;
    name: string;
  };
}

export interface PublishProps {
  pageNumber: number;
  pageSize: number;
  search: string; // 搜索的关键字
  role: 'driver' | 'passenger';
  des: 'startLocation' | 'endLocation' | 'all'; // 出发地或者目的地 startLocation： 出发地 endLocation： 目的地 all: 所有数据
  map: Local;
}
@Injectable()
export class FormService {
  constructor(
    @InjectRepository(Publish)
    private FormRepository: Repository<Publish>,

    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async addForm(data: Publish): Promise<any> {
    try {
      // const user_id: number = data.user.id;
      console.log('新发布一条', data);
      data.created_at = new Date();
      const user_id: number = data.user_id;
      const user = await this.usersRepository.findOne({
        where: { id: user_id },
      });
      const form = new Publish();
      form.user = user;
      await this.FormRepository.save(data);
    } catch (error) {
      console.log('新增报错', error);
      return {
        code: 500,
        message: error,
      };
    }
  }

  async publishPage(params: PublishProps): Promise<any> {
    try {
      const { search, pageNumber, pageSize, role, des, map } = params;
      const skip = (pageNumber - 1) * pageSize;

      type Generator = (key: 'start' | 'end', map: PublishProps['map']) => any;
      // 根据map找到最后一级
      const generator: Generator = (key = 'start', local) => {
        if (local['county'] && Object.keys(local['county']).length) {
          return {
            [key + 'County']: local['county'],
          };
        }
        if (local['city'] && Object.keys(local['city']).length) {
          return {
            [key + 'City']: map['city'],
          };
        }
        if (local['province'] && Object.keys(local['province']).length) {
          return {
            [key + 'Province']: local['province'],
          };
        }
      };

      let query = this.FormRepository.createQueryBuilder('publish');
      // 按照创建时间降序排列
      query = query.orderBy('publish.created_at', 'DESC');
      if (search) {
        query = query.where(
          'publish.startLocation LIKE :search OR publish.endLocation LIKE :search',
          { search: `%${search}%` },
        );
      }
      if (role) {
        query = query.andWhere('publish.role = :role', { role });
      }

      if (des === 'all') {
        // 全部
      }

      function generateEndCityQuery(
        fieldName: string,
        endCity: string,
      ): string {
        return `JSON_UNQUOTE(JSON_EXTRACT(${fieldName}, "$.code")) = :${endCity}`;
      }

      if (des === 'startLocation') {
        // 出发地.
        const startLocaEndData = generator('start', map);
        console.log('startLocaEndData', startLocaEndData);
        if (startLocaEndData) {
          if (
            startLocaEndData?.startProvince &&
            startLocaEndData.startProvince.code !== '00' // 如果省选择了全国，那么就查所有
          ) {
            const startProvinceQuery = generateEndCityQuery(
              'publish.startProvince',
              'startProvince',
            );
            query = query.andWhere(startProvinceQuery, {
              startProvince: startLocaEndData.startProvince.code,
            });
          }
          if (startLocaEndData?.startCity) {
            const startCityQuery = generateEndCityQuery(
              'publish.startCity',
              'startCity',
            );
            query = query.andWhere(startCityQuery, {
              startCity: startLocaEndData.startCity.code,
            });
          }
          if (startLocaEndData?.startCounty) {
            const startCountyQuery = generateEndCityQuery(
              'publish.startCounty',
              'startCounty',
            );
            query = query.andWhere(startCountyQuery, {
              startCounty: startLocaEndData.startCounty.code,
            });
          }
        }
      }

      if (des === 'endLocation') {
        // 目的地
        const destLocaEndData = generator('end', map);
        console.log('destLocaEndData', destLocaEndData);
        if (destLocaEndData) {
          if (
            destLocaEndData?.endProvince &&
            destLocaEndData.endProvince.code !== '00' // 如果省选择了全国，那么就查所有
          ) {
            const endProvinceQuery = generateEndCityQuery(
              'publish.endProvince',
              'endProvince',
            );
            query = query.andWhere(endProvinceQuery, {
              endProvince: destLocaEndData.endProvince.code,
            });
          }

          if (destLocaEndData?.endCity) {
            const endCityQuery = generateEndCityQuery(
              'publish.endCity',
              'endCity',
            );
            query = query.andWhere(endCityQuery, {
              endCity: destLocaEndData.endCity.code,
            });
          }

          if (destLocaEndData?.endCounty) {
            const endCountyQuery = generateEndCityQuery(
              'publish.endCounty',
              'endCounty',
            );
            query = query.andWhere(endCountyQuery, {
              endCounty: destLocaEndData.endCounty.code,
            });
          }
        }
      }

      const [results, total] = await query
        .skip(skip)
        .take(pageSize)
        .getManyAndCount();
      return {
        code: 200,
        data: {
          list: results,
          total: total,
        },
        message: 'ok',
      };
    } catch (error) {
      console.log('获取列表报错');
      return {
        code: 500,
        message: error,
      };
    }
  }

  async upateTypeCount(
    publish_id: string | number,
    data: UpdateType,
  ): Promise<any> {
    // 使用 TypeORM 的 update 方法来更新数据
    const publish_item = await this.FormRepository.findOne({
      where: { id: Number(publish_id) },
    });

    if (!publish_item) {
      return {
        code: 1000,
        data: null,
        message: `此id(${publish_id})不存在}`,
      };
    }
    switch (data.type) {
      case 'rocket':
        publish_item.rocket = publish_item.rocket ? publish_item.rocket + 1 : 1;
        break;
      case 'collect':
        publish_item.collect = publish_item.collect
          ? publish_item.collect + 1
          : 1;
        break;
      case 'report':
        publish_item.report = publish_item.report ? publish_item.report + 1 : 1;
        break;
      default:
        return {
          code: 500,
          data: null,
          message: '更新数据报错',
        };
        throw new Error('Invalid field type');
    }
    const res = await this.FormRepository.save(publish_item);
    console.log("是否已经更新到publish表了", res);
    // return {
    //   code: 200,
    //   data: res,
    //   message: '更新数据完成',
    // 更新users表中的对应的字段
    const user = await this.usersRepository.findOne({
      where: { id: Number(data.userId) },
    });

    if (!user) {
      throw new Error('用户不存在');
    }
    if (data.type === 'rocket') {
      if (!Array.isArray(user.rocket)) {
        user.rocket = [];
      }
      user.rocket.push(`${publish_id}`);
    }
    if (data.type === 'collect') {
      if (!Array.isArray(user.collects)) {
        user.collects = [];
      }
      user.collects.push(`${publish_id}`);
    }
    if (data.type === 'report') {
      if (!Array.isArray(user.reports)) {
        user.reports = [];
      }
      user.reports.push(`${publish_id}`);
    }
    const saveUsered = await this.usersRepository.save(user);
    console.log('是否已经更新到用户表了', saveUsered)
    if (saveUsered) {
      return {
        code: 200,
        data: null,
        message: 'ok',
      };
    } else {
      return {
        code: 500,
        data: null,
        message: 'error',
      };
    }
  }
}
